<?php
declare (strict_types = 1);

namespace app\index\controller;
use think\facade\View;
use think\facade\Db;
use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Config;

use app\common\model\Category as CategoryModel;
use app\common\model\Users as UsersModel;
use app\common\model\Sms as SmsModel;
use app\common\model\Message as MessageModel;
use app\common\model\Order as OrderModel;
use app\common\model\Lists as ListsModel;

use app\admin\validate\Users as validateUsers;

class Users extends Base
{

    protected $middleware = [
        'CountTime' => ['only' 		=> ['user_center_order'] ],
    ];

    function __construct(){

        parent::__construct();

        if(cookie('user_id')){
            $UsersModel = new UsersModel();
            $user_info = $UsersModel -> where('id','=',cookie('user_id'))->find();
            View::assign('user_info',$user_info);
        }
    }



    public function register(){
        if(IS_AJAX){
            $param = input('param.');

            $validate = new validateUsers();
            $result = $validate->scene('register')->batch(false)->check($param);
            if(!$result){
                return dyajaxReturn(0,$validate->getError());
            }

            $vertify = $param['vertify'];
            if( !captcha_check($vertify)) {
                return dyajaxReturn(0,'图形验证码错误');
            }

            //验证短信验证码
            $SmsModel = new SmsModel();
            $is_sms = $SmsModel ->checkSmsCode($param['registermobile'],$param['code'],'register');
            if(!$is_sms['code']){
                return dyajaxReturn(0,$is_sms['msg']);
            }

            $model = new UsersModel();
            $param['mobile'] = $param['registermobile'];
            $res = $model -> handle($param);
            return dyajaxReturn($res['code'],$res['msg']);
        }else {
            return View::fetch('index/register');
        }
    }

    //扫码登录
    public function login(){

        $domain = request()->domain();
//        dump($domain);
        View::assign('domain', $domain);
        return View::fetch('index/login');
    }

    //密码登录
    public function login1(){
        if(IS_POST){
            $param = input('param.');

            $validate = new validateUsers();
            $result = $validate->scene('login1')->batch(false)->check($param);
            if(!$result){
                return dyajaxReturn(0,$validate->getError());
            }

            $vertify = $param['vertify'];
            if( !captcha_check($vertify)) {
                return dyajaxReturn(0,'图形验证码错误');
            }

            $model = new UsersModel();
            $res = $model->login($param['mobile'],$param['password']);
            return dyajaxReturn($res['code'],$res['msg']);
        }else {
            return View::fetch('index/login1');
        }
    }

    //验证码登录
    public function login2(){
        if(IS_POST){
            $param = input('param.');

            $validate = new validateUsers();
            $result = $validate->scene('login2')->batch(false)->check($param);
            if(!$result){
                return dyajaxReturn(0,$validate->getError());
            }

            $vertify = $param['vertify'];
            if( !captcha_check($vertify)) {
                return dyajaxReturn(0,'图形验证码错误');
            }

            //验证短信验证码
            $SmsModel = new SmsModel();
            $is_sms = $SmsModel ->checkSmsCode($param['mobile'],$param['code'],'login2');
            if(!$is_sms['code']){
                return dyajaxReturn(0,$is_sms['msg']);
            }

            $model = new UsersModel();
            $res = $model->login($param['mobile']);
            return dyajaxReturn($res['code'],$res['msg']);
        }else {
            return View::fetch('index/login2');
        }
    }

    //忘记密码
    public function forgetpwd(){
        if(IS_POST){
            $param = input('param.');

            $validate = new validateUsers();
            $result = $validate->scene('forgetpwd')->batch(false)->check($param);
            if(!$result){
                return dyajaxReturn(0,$validate->getError());
            }

            //验证短信验证码
            $SmsModel = new SmsModel();
            $is_sms = $SmsModel ->checkSmsCode($param['forget_mobile'],$param['code'],'forgetpwd');
            if(!$is_sms['code']){
                return dyajaxReturn(0,$is_sms['msg']);
            }

            $model = new UsersModel();
            $res = $model->forgetpwd($param);
            return dyajaxReturn($res['code'],$res['msg']);
        }else{
            return View::fetch('index/forgetpwd');
        }
    }


    //退出登录
    public function loginout(){
//        session_unset();
//        session(null);
//        \think\facade\Session::clear();

        cookie('user_id', null);
        cookie('name', null);
        cookie('mobile', null);
        cookie('token', null);

        $this->redirect("/index/index");
    }

    //个人中心
    public function user_center(){

        View::assign('action','user_center');
        return View::fetch('index/user_center');
    }

    //个人中心-编辑
    public function user_center_edit(){
        if(IS_POST){
            $param = input("param.");
            $UsersModel = new UsersModel();
            $u = $UsersModel->where('id','<>',$param['id'])->where('mobile','=',$param['mobile'])->find();
            if($u['id']){
                return dyajaxReturn(0,'已有其他用户使用此手机');
            }
            $res = $UsersModel->handle($param);
            return dyajaxReturn($res['code'],$res['msg']);
        }else {
            View::assign('action', 'user_center');
            return View::fetch('index/user_center_edit');
        }
    }

    //个人中心-订单
    public function user_center_order(){
        $param = input("param.");
        $OrderModel = new OrderModel();
        $param['user_id'] = cookie('user_id');
        $param['pay_status'] = isset($param['pay_status'])?$param['pay_status']:'';
        $res = $OrderModel->tableData($param);
        View::assign('page',$res['page']);
        View::assign('res',$res['data']);

        View::assign('action','user_center_order');
        return View::fetch('index/user_center_order');
    }

    //个人中心-订单-订单详情
    public function user_center_order_details(){

        $param = input("param.");
        $id = $param['id'];

        $OrderModel = new OrderModel();
        $info = $OrderModel->info($id);

        $ListsModel = new ListsModel();
        $lists_one = $ListsModel -> where('id','=',$info['lists_id'])->find();

        $info['type'] = $lists_one['type'];
        $info['cate_id'] = $lists_one['cate_id'];
        $info['duration'] = $lists_one['duration'];
        $info['effective_date'] = $lists_one['effective_date'];
        $info['sign_up_num'] = $lists_one['sign_up_num'];
        if($info['pay_time'] != ''){
            $info['pay_time'] = date('Y-m-d H:i',$info['pay_time']);
        }
        $info['add_time'] = date('Y-m-d H:i',$info['add_time_o']);
        if($info['un_time']) {
            $info['un_time'] = date('Y-m-d H:i', $info['un_time']);
        }
        View::assign('info',$info);

        View::assign('action','user_center_order');
        return View::fetch('index/user_center_order_details');
    }

    //个人中心-系统通知
    public function user_center_system(){
        $param = input("param.");
        $MessageModel = new MessageModel();
        $param['is_open'] = 1;
        $param['limit'] = 4;
        $res = $MessageModel->tableData($param);

        View::assign('page',$res['page']);
        View::assign('res',$res['data']);

        View::assign('action','user_center_system');
        return View::fetch('index/user_center_system');
    }

    //个人中心-账号安全
    public function user_center_safe(){

        View::assign('action','user_center_safe');
        return View::fetch('index/user_center_safe');
    }

    //个人中心-修改用户手机
    public function user_center_update_mobile(){
        if(IS_POST) {
            $param = input("param.");
            $validate = new validateUsers();
            $result = $validate->scene('udpate_mobile')->batch(false)->check($param);
            if (!$result) {
                return dyajaxReturn(0, $validate->getError());
            }

            //旧手机验证短信验证码
            $SmsModel = new SmsModel();
            $is_sms = $SmsModel ->checkSmsCode($param['old_mobile'],$param['old_code'],'old_code');
            if(!$is_sms['code']){
                return dyajaxReturn(0,$is_sms['msg']);
            }

            //新手机验证短信验证码
            $SmsModel = new SmsModel();
            $is_sms = $SmsModel ->checkSmsCode($param['new_mobile'],$param['new_code'],'new_code');
            if(!$is_sms['code']){
                return dyajaxReturn(0,$is_sms['msg']);
            }

            $UsersModel = new UsersModel();
            $res = $UsersModel -> update_mobile($param);
            return dyajaxReturn($res['code'],$res['msg']);
        }else {
            View::assign('action', 'user_center_safe');
            return View::fetch('index/user_center_update_mobile');
        }
    }

    //密码修改
    public function user_center_update_pwd(){
        if(IS_POST){
            $param = input("param.");

            $validate = new validateUsers();
            $result = $validate->scene('udpate_pwd')->batch(false)->check($param);
            if (!$result) {
                return dyajaxReturn(0, $validate->getError());
            }

            $UsersModel = new UsersModel();
            $res = $UsersModel -> update_pwd($param);
            return dyajaxReturn($res['code'],$res['msg']);
        }else {
            View::assign('action', 'user_center_safe');
            return View::fetch('index/user_center_update_pwd');
        }
    }

    //扫码第一次登录 绑定手机
    public function bind_phone(){
        $param = input('param.');
        if(IS_POST){
            $vertify = $param['vertify'];
            if( !captcha_check($vertify)) {
                return dyajaxReturn(0,'图形验证码错误');
            }

            //验证短信验证码
            $SmsModel = new SmsModel();
            $is_sms = $SmsModel ->checkSmsCode($param['mobile'],$param['code'],'bind_phone');
            if(!$is_sms['code']){
                return dyajaxReturn(0,$is_sms['msg']);
            }
            $mobile = $param['mobile'];
//            $wxinfo = json_decode($param['wxuser_json'],true);
            $unionid = $param['unionid'];

            $UsersModel = new UsersModel();
            $u_one = $UsersModel -> where('mobile','=',$mobile)->where('is_open','=',1)->find();
            if(!$u_one['id']){
                //没有此账号就创建
                $data['name'] = $mobile;
                $data['mobile'] = $mobile;
                //$data['head_pic'] = $wxinfo['head_pic'];
                $data['password'] = md5(md5('123456'));
                $data['unionid'] = $unionid;
                $data['add_time'] = time();
                $data['sort'] = $UsersModel ->max('sort') + 1;

                $id = $UsersModel->insertGetId($data);
                if(!$id){
                    return dyajaxReturn(0,'绑定失败');
                }
                $info = $UsersModel->where("id",'=',$id)->find();
            }else{
                //有此账号，修改unionid
                $data['unionid'] = $unionid;
                $data['update_time'] = time();
                $res = $UsersModel -> where('id','=',$u_one['id'])->update($data);
                if(!$res){
                    return dyajaxReturn(0,'绑定失败');
                }
                $info = $u_one;
            }
            $UsersModel->setCacheAndToekn($info);
            return dyajaxReturn(1,'绑定成功',$info);
        }else{
            View::assign('unionid', $param['unionid']);
            return View::fetch('index/bind_phone');
        }
    }

}
